var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cors = require('cors'); 
var userModel = require('./model/user')
var cookieParser = require('cookie-parser');
var jwtAuth = require('./utils/jwt');  // 用来验证身份是否有效
var jwt = require('jsonwebtoken');
var logger = require('morgan');

// 在路由请求之前连接数据库
require('./db')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var movieRouter = require('./routes/movie');
var typeRouter = require('./routes/types')
var regionRouter = require('./routes/region')
var languageRouter = require('./routes/language')

var cinemaRouter = require('./routes/cinema')
var orderRouter = require('./routes/order')
var rolesRouter = require('./routes/roles')
var activityRouter = require('./routes/activity')
var menuRouter = require('./routes/menu')

var app = express();

// view engine setup 模版引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');  // 指定模版引擎

app.use(cors());   // 使用cors中间件 , 支持跨域
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 // 静态资源服务器
app.use('/upload',express.static(path.join(__dirname,'upload')));
app.use(jwtAuth);   // 在加载路由之前验证token

// 使用中间件 绑定 token信息
app.use(async (req,res,next)=>{
  let authorization = req.get('authorization');

  // 排除登录和注册
  console.log(req.path,'接口地址');
  if(req.path.includes('/users/reg') ||req.path.includes('/users/login')  || req.path.includes('/roles/findRoles') ) {
    next();
    return;
  }
  console.log(req.path.includes('/users/login'),'授权了吗');
  if(authorization){
    const token =  authorization.slice(7).trim();
     jwt.verify(token,'suibian',async (err,user)=>{
        if(err){
          if (err.name === 'TokenExpiredError') {
            return res.status(401).json({ message: 'Token expired. Please log in again.' });
          }
          return res.status(403).json({ message: 'Invalid token error.' });
        }

        req.userphone = user.phone;
        let resData = await userModel.findOne({phone:user.phone})
        req.userId = resData._id;
        console.log(req.userId,'当前的id');
        next(); 
    });
    
  }  else {
    res.sendStatus(401); // 如果没有 token，则返回 401
  }
 
})

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.use('/movie',movieRouter);
app.use('/type',typeRouter);
app.use('/region',regionRouter);
app.use('/language',languageRouter);
app.use('/cinema',cinemaRouter);
app.use('/order',orderRouter);
app.use('/roles',rolesRouter);
app.use('/activity',activityRouter);
app.use('/menu',menuRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理中间件
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401).json({ message: 'token无效' });
  }
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
  // res.render 是用来渲染模版
});

module.exports = app;
